package maosy.poi.test

import org.junit.Test
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import javax.mail.Header
import javax.mail.Multipart
import javax.mail.Session
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage


class JXmailTest {

    @Test
    fun test() {
        val path = "/Users/mario/Downloads/E558王汝飞.doc"
        val fileInputStream = FileInputStream(File(path))
        val mailSession = Session.getDefaultInstance(System.getProperties(), null)
        val msg = MimeMessage(mailSession, fileInputStream)
        val content = msg.content
        if (content is Multipart) {
            content.apply {
                val part: MimeBodyPart = this.getBodyPart(0) as MimeBodyPart
                val strEncoding = getEncoding(part)
                val html = getHtmlText(part, strEncoding)
                println(strEncoding)
                println(html)
            }
        }
    }

    private fun getHtmlText(part: MimeBodyPart, encoding: String): String {
        val reader = BufferedReader(InputStreamReader(part.inputStream, encoding))
        reader.lines().forEach {
            println(it)
        }
        return ""
    }


    private fun getEncoding(part: MimeBodyPart): String {
        val headers = part.allHeaders
        while (headers.hasMoreElements()) {
            val head: Header = headers.nextElement() as Header
            if (head.name == "Content-Type") {
                val strType = head.value
                val pos = strType.indexOf("charset=")
                if (pos >= 0) {
                    var strEncoding = strType.substring(
                        pos + 8,
                        strType.length
                    )
                    if (strEncoding.startsWith("\"") || strEncoding.startsWith("\'")) {
                        strEncoding = strEncoding.substring(
                            1,
                            strEncoding.length
                        )
                    }
                    if (strEncoding.endsWith("\"") || strEncoding.endsWith("\'")) {
                        strEncoding = strEncoding.substring(
                            0,
                            strEncoding.length - 1
                        )
                    }
                    if (strEncoding.toLowerCase().compareTo("gb2312") == 0) {
                        strEncoding = "gbk"
                    }
                    return strEncoding
                }
            }
        }
        return ""
    }

}